package deep8jvmdvm;

/*
synchronized

synchronized 可以用来修饰以下 3 个层面：

修饰实例方法；
锁对象是当前实例对象，因此只有同一个实例对象调用此方法才会产生互斥效果，不同实例对象之间不会有互斥效果

修饰静态类方法；

修饰代码块。
 */

import utils.PrintlnUtils;

public class TestSynchronized2 {

    public static void main(String[] args) {
        TestSynchronized2 testSynchronized1 = new TestSynchronized2();
        TestSynchronized2 testSynchronized2 = new TestSynchronized2();

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                testSynchronized1.printLog();
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                testSynchronized2.printLog();
            }
        });
        thread1.start();
        thread2.start();

        /*
        不同实例对象之间不会有互斥效果

        在不同的线程中调用的是不同对象的 printLog 方法，因此彼此之间不会有排斥。运行效果如下：

            Thread-1 is printing 0

            Thread-0 is printing 0

            Thread-1 is printing 1

            Thread-0 is printing 1

            Thread-0 is printing 2

            Thread-1 is printing 2

            Thread-0 is printing 3

            Thread-1 is printing 3

            Thread-0 is printing 4

            Thread-1 is printing 4


            可以看出，两个线程是交互执行的。

         */
    }

    public synchronized void printLog() {
        try {
            for (int i = 0; i < 5; i++) {
                PrintlnUtils.println(Thread.currentThread().getName() + " is printing " + i);
                Thread.sleep(300);
            }
        } catch (Exception e) {

        }
    }

}
